package com.gcxy.exception.handler;

import com.gcxy.core.R;
import com.gcxy.enums.ResultCodeEnum;
import com.gcxy.exception.annotation.GlobalException;
import com.gcxy.exception.global.IGlobalException;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

/**
 * Copyright (C), 2024-2024, BUG闭退！
 * Author: Huang先森
 * Date: 2024/7/22 13:28
 * FileName: BindExceptionHandler
 * Description: * 绑定异常
 *  * 对 BindException 异常信息的扩展处理
 *  * BindException：通常错误发生在端口正在使用中或无法分配所请求的本地地址时
 */
@GlobalException(throwable = BindException.class)
public class BindExceptionHandler implements IGlobalException<R, BindException> {

    @Override
    public R exception(BindException throwable, HttpServletRequest request, HttpServletResponse response) {
        return BaseThrowExceptionHandler.exception(throwable, ResultCodeEnum.REQUEST_PARAM_ERROR, () -> {
                    List<String> messageList = Lists.newArrayList();
                    List<FieldError> fieldErrors = throwable.getBindingResult().getFieldErrors();
                    Optional.ofNullable(fieldErrors).ifPresent(fieldErrorList -> {
                        fieldErrorList.stream().forEach(error -> {
                            String typeName = error.getClass().getSimpleName();
                            if ("FieldError".equals(typeName)) {
                                FieldError fieldError = (FieldError) error;
                                String[] codes = fieldError.getCodes();
                                String type = "";
                                if (codes.length > 3) {
                                    type = codes[2].substring(codes[2].lastIndexOf(".") + 1);
                                }
                                messageList.add(String.format("请求参数名:%s,类型:%s,请求参数值:%s与参数类型不匹配", fieldError.getField(), type, fieldError.getRejectedValue()));
                            } else {
                                messageList.add(error.getDefaultMessage());
                            }
                        });
                    });
                    return Joiner.on(",").join(messageList);
                }
        );
    }
}